package exploit

import (
	"fmt"
	"os"
	"path/filepath"
	"scan2html/internal/epss"
	"scan2html/internal/common"
	"scan2html/internal/logger"
)

func PrepareExploitDataTemporarily() (string, error) {
	return prepareExploitData(os.TempDir())
}

func PrepareExploitDataForCaching() (string, error) {
	pathToPluginDir, _ := common.GetPathToPluginDir()
	return prepareExploitData(pathToPluginDir)
}


// PrepareExploitData downloads the CISA dataset, saves it as a temporary file,
func prepareExploitData(basePath string) (string, error) {
	const (
		cisaURL      = "https://www.cisa.gov/sites/default/files/feeds"
		cisaFileName = "known_exploited_vulnerabilities.json"
	)

	// Define paths
	tmpCisaFilepath := filepath.Join(basePath, cisaFileName)
	cisaDownloadUrl := fmt.Sprintf("%s/%s", cisaURL, cisaFileName)
	logger.Logger.Infof("Downloading Exploit data from: %s\n", cisaDownloadUrl)

	if err := epss.DownloadFile(cisaDownloadUrl, tmpCisaFilepath); err != nil {
		return "", err
	}

	stats, _ := os.Stat(tmpCisaFilepath)
	logger.Logger.Infof("Exploit data downloaded successfully to %s with size of: %d bytes\n", tmpCisaFilepath, stats.Size())

	return tmpCisaFilepath, nil
}